// frontend/src/stores/chat.ts
import { defineStore } from 'pinia';
import { ALL_TAGS, MODELS, API_BASE_URL } from '@/config/api';
import type { ModelKey } from '@/config/api';

export type Message = { role: 'user' | 'assistant' | 'system'; content: string; };
export type Session = { id: string; title: string; created_at: string; updated_at: string; module?: string; };

type ApiListSessionsResp = { sessions: Session[] };
type ApiGetMessagesResp = { messages: Message[] };
type ApiCreateSessionResp = { id: string };

export const useChatStore = defineStore('chat', {
  state: () => ({
    model: 'blockchain' as ModelKey,
    sessions: [] as Session[],
    currentSessionId: '' as string,
    messages: [] as Message[],
    streaming: false as boolean,
    showMedicalPanel: false as boolean,
    showRegulationPanel: false as boolean,
    currentModule: 'blockchain' as string,
  }),
  getters: {
    activeModelTags(state){
      const tags = MODELS[state.model].tags;
      return tags;
    },
    allTags(){ return ALL_TAGS; },
    currentSession(state){
      return state.sessions.find(s => s.id === state.currentSessionId) || null;
    },
  },
  actions: {

    setModel(m: ModelKey){
      this.model = m; 
      // 根据模型类型自动设置currentModule
      if (m === 'medical') {
        this.currentModule = 'medical';
      }else if (m === 'blockchain') {
        this.currentModule = 'blockchain';
      } else if (m === 'supervision') {
        this.currentModule = 'supervision';
      } else if (m === 'video') {
        this.currentModule = 'video';
      } else if (m === 'math') {
        this.currentModule = 'math';
      } else if (m === 'metrology') {
        this.currentModule = 'metrology';
      } else if (m === 'codeaudit') {
        this.currentModule = 'codeaudit';
      } else {
        this.currentModule = 'default';
      }
    },
    setCurrentModule(module: string){ this.currentModule = module; },

    setSessions(list: Session[]){ this.sessions = list; },
    setCurrentSession(id: string){ this.currentSessionId = id; },
    setMessages(msgs: Message[]){ this.messages = msgs; },
    appendMessage(m: Message){ this.messages.push(m); },
    updateLastAssistantDelta(delta: string){
      for (let i = this.messages.length - 1; i >= 0; i--) {
        if (this.messages[i].role === 'assistant') {
          this.messages[i] = { ...this.messages[i], content: this.messages[i].content + delta };
          return;
        }
      }
    },
    // 完全替换最后一条消息的内容（用于翻译后更新）
    updateLastMessageContent(content: string){
      for (let i = this.messages.length - 1; i >= 0; i--) {
        if (this.messages[i].role === 'assistant') {
          console.log('updateLastMessageContent', content);
          this.messages[i] = { ...this.messages[i], content: content };
          return;
        }
      }
    },
    setStreaming(v: boolean){ this.streaming = v; },
    setShowMedicalPanel(v: boolean){ this.showMedicalPanel = v; },
    setShowRegulationPanel(v: boolean){ this.showRegulationPanel = v; },

    /** 拉取会话列表（不自动选中） */
    async fetchSessions(){
      console.log('fetchSessions', this.currentModule);
      // 使用当前模块参数获取对应的会话列表
      const module = this.currentModule || 'default';
      const r = await fetch(`${API_BASE_URL}/api/sessions?module=${encodeURIComponent(module)}`);
      if (!r.ok) throw new Error(`fetchSessions HTTP ${r.status}`);
      const data = (await r.json()) as ApiListSessionsResp;
      const list = (data.sessions ?? []).slice().sort(
        (a,b) => +new Date(b.updated_at) - +new Date(a.updated_at)
      );
      this.setSessions(list);
      if (!this.currentSessionId) this.setMessages([]);
    },

    /** 读取会话消息 */
    async fetchMessages(sessionId: string){
      if (!sessionId) return;
      // 从会话对象获取模块信息，如果没有则使用当前模块
      const session = this.sessions.find(s => s.id === sessionId);
      const module = session?.module || this.currentModule || 'default';
      const r = await fetch(`${API_BASE_URL}/api/sessions/${sessionId}?module=${encodeURIComponent(module)}`);
      if (!r.ok) throw new Error(`fetchMessages HTTP ${r.status}`);
      const data = (await r.json()) as ApiGetMessagesResp;
      this.setMessages(data.messages ?? []);
    },

    /** 新建会话（后端返回 {id}） */
    async createSession(){
      // 使用当前模块
      const module = this.currentModule || 'default';
      const r = await fetch(`${API_BASE_URL}/api/sessions`, {
        method: 'POST',
        headers: { 'Content-Type':'application/json' },
        body: JSON.stringify({ module })
      });
      if (!r.ok) throw new Error(`createSession HTTP ${r.status}`);
      const data = (await r.json()) as ApiCreateSessionResp;
      const id = data.id;
      // 立刻刷新列表（拿到 title/时间）
      await this.fetchSessions();
      this.setCurrentSession(id);
      this.setMessages([]);
      return id;
    },

    /** 切换会话 */
    async selectSession(id: string){
      // 设置当前会话ID
      this.setCurrentSession(id);
      
      // 从会话对象中提取模块信息并更新currentModule
      const session = this.sessions.find(s => s.id === id);
      if (session && session.module) {
        this.setCurrentModule(session.module);
        // 根据模块类型更新医疗面板显示状态
        this.setShowMedicalPanel(session.module === 'medical');
      }
      
      // 获取会话消息
      await this.fetchMessages(id);
    },

    /** 置顶（页面 send 调用时会用到） */
    touchSession(id: string){
      const idx = this.sessions.findIndex(s => s.id === id);
      if (idx < 0) return;
      const item = { ...this.sessions[idx], updated_at: new Date().toISOString() };
      this.sessions.splice(idx, 1);
      this.sessions.unshift(item);
    },

    /** 重命名（后端返回 {ok:true}，本地更新并置顶） */
    async renameSession(id: string, title: string){
      // 从会话对象获取模块信息，如果没有则使用当前模块
      const session = this.sessions.find(s => s.id === id);
      const module = session?.module || this.currentModule || 'default';
      const r = await fetch(`${API_BASE_URL}/api/sessions/${id}?module=${encodeURIComponent(module)}`, {
        method: 'PATCH',
        headers: { 'Content-Type':'application/json' },
        body: JSON.stringify({ title }),
      });
      if (!r.ok) throw new Error(`renameSession HTTP ${r.status}`);
      const idx = this.sessions.findIndex(s => s.id === id);
      if (idx >= 0) {
        const updated = { ...this.sessions[idx], title, updated_at: new Date().toISOString() };
        this.sessions.splice(idx, 1);
        this.sessions.unshift(updated); // 置顶
      }
      if (this.currentSessionId === id) {
        // 当前会话重命名时，不动消息；只更新标题即可
      }
    },

    /** 删除（若删的是当前会话则清空当前） */
    async deleteSession(id: string){
      // 从会话对象获取模块信息，如果没有则使用当前模块
      const session = this.sessions.find(s => s.id === id);
      const module = session?.module || this.currentModule || 'default';
      const r = await fetch(`${API_BASE_URL}/api/sessions/${id}?module=${encodeURIComponent(module)}`, { method: 'DELETE' });
      if (!r.ok) throw new Error(`deleteSession HTTP ${r.status}`);
      const idx = this.sessions.findIndex(s => s.id === id);
      if (idx >= 0) this.sessions.splice(idx, 1);
      if (this.currentSessionId === id) {
        this.setCurrentSession('');
        this.setMessages([]);
      }
    },
  }
});
